<?php
/**
 * 功能描述：	系统模型管理
 * @datetime	2022-07-10
 * @version   	v2.3.0
 * @author   	ZHL
 * @copyrigh  	2022 ZHL 版权所有
 */

class Admin_MouldServe extends Model {

    /**
     * Notes:模型列表页
     * User: ZhuHaili
     */
    function getMouldsList($status = 0){
        $sysmould = new Admin_MouldModels();
        $list = $sysmould->getMouldsList($status);
        $statusArr = BaseData::$statusArr;
        if(!empty($list)){
            foreach($list as $k=>$v){
                $list[$k]['mouldtypetxt'] = $v['mouldtype'] == 1 ? '系统模型' : '通用模型';
                $list[$k]['classflagtxt'] = $v['classflag'] == 1 ? '已开' : '未开';
                $list[$k]['tmplflagtxt'] = $v['tmplflag'] == 1 ? '已开' : '未开';
                $list[$k]['statustxt'] = $statusArr[$v['status']];
            }
        }
        return $list;
	}

    /**
     * Notes:模型详情-根据模型编码
     * User: ZhuHaili
     * Date: 菜单
     */
    function getMouldsInfoToCode($sysmouldCode){
        if(!$sysmouldCode){
            return array();
        }
        $sysmould = new Admin_MouldModels();
        return $sysmould->getMouldsInfoToCode($sysmouldCode);
    }

    /**
     * Notes:模型详情-根据id查询
     * User: ZhuHaili
     */
    function getMouldsInfo($id){
        if(!$id){
            return array();
        }
        $sysmould = new Admin_MouldModels();
        return $sysmould->getMouldsInfo($id);
    }

    /**
     * Notes:删除模型
     * User: ZhuHaili
     * Date: 菜单
     */
    function delMoulds($id){
        $id = intval($id);
        if(!$id){
            return '指定ID不能为空';
        }
        $info = $this->getMouldsInfo($id);
        if(empty($info)){
            return '当前模型已不存在';
        }
        if($info['mouldtype'] == 1){
            return '当前为系统模型禁止删除';
        }
        $db = $this->conn('mysql');
        $result = $db->delData('sysmould', array('id'=>$id));
        if(!$result){
            return '删除失败，刷新重试';
        }
        //删除对应的表
        $tableFix = $db->db_fix.$info['mouldcode'];
        $this->delTable($tableFix);
        $this->delTable($tableFix.'_detail');
        //////
        if($info['classflag'] == '1'){
            $this->delTable($tableFix.'_class');
        }
        if($info['tmplflag'] == '1'){
            $this->delTable($tableFix.'_list');
        }
        return 'Y';
    }

    /**
     * Notes:模型排序
     * User: ZhuHaili
     */
    function seqMoulds($mouldCode, $param){
        if(!is_array($param)){
            return '排序失败';
        }
        foreach($param as $id=>$seq){
            $where['id'] = $id;
            $data['viewseq'] = intval($seq);
            $this->conn('mysql')->updateData($mouldCode, $data, $where);
        }
        return 'Y';
    }

    /**
     * Notes:添加模型
     * User: ZhuHaili
     */
    function addMoulds($param){
        // 数据验证
        if (!isset($param['mouldname']) || !$param['mouldname']) {
            return '模型名称不能为空';
        }
        if (!isset($param['mouldcode']) || !$param['mouldcode']) {
            return '模型编码不能为空';
        }
        if(!preg_match("/^[a-zA-Z]([a-zA-Z0-9_]+)?$/", $param['mouldcode'])) {
            return '模型编码格式不正确';
        }
        $info = $this->getMouldsInfoToCode($param['mouldcode']);
        if (!empty($info)) {
            return '模型已存在';
        }
        $classflag = intval($param['classflag']) == '1' ? '1' : '2';
        $sideflag = intval($param['sideflag']) == '1' ? '1' : '2';
        $tmplflag = intval($param['tmplflag']) == '1' ? '1' : '2';
        $status = intval($param['status']) == '1' ? '1' : '2';
        $viewseq = intval($param['viewseq']);
        // 数据添加
        $data['createdate'] = date('Y-m-d H:i:s');
        $data['mouldname'] = $param['mouldname'];
        $data['mouldcode'] = $param['mouldcode'];
        $data['classflag'] = $classflag;
        $data['sideflag'] = $sideflag;
        $data['tmplflag'] = $tmplflag;
        $data['viewseq'] = $viewseq;
        $data['status'] = $status;
        $data['mouldtype'] = '2';
        $db = $this->conn('mysql');
        $result = $db->addData('sysmould', $data);
        if (!$result) {
            return '模型配置信息保存失败';
        }
        $tableCode = $db->db_fix.$data['mouldcode'];
        $tableName = $data['mouldname'];
        // 创建主表
        $mainRes = $this->createTableMain($tableCode, $tableName);
        if($mainRes != 'Y'){return $mainRes;}
        // 创建副表
        $viceRes = $this->createTableVice($tableCode, $tableName);
        if($viceRes != 'Y'){return $viceRes;}
        // 创建文章多菜单关联表
        if($classflag == '1'){
            $classRes = $this->createTableClass($tableCode, $tableName);
            if($classRes != 'Y'){return $classRes;}
        }
        // 创建子集列表关联表
        if($sideflag == '1'){
            $sideRes = $this->createTableSide($tableCode, $tableName);
            if($sideRes != 'Y'){return $sideRes;}
        }
        // 创建详情列表自定义模版关联表
        if($tmplflag == '1'){
            $listRes = $this->createTableList($tableCode, $tableName);
            if($listRes != 'Y'){return $listRes;}
        }
        return 'Y';
    }

    /**
     * Notes:修改模型
     * User: ZhuHaili
     */
    public function updateMoulds($param){
        // 数据验证
        if (!isset($param['id']) || !$param['id']) {
            return '模型ID不能为空';
        }
        if (!isset($param['mouldname']) || !$param['mouldname']) {
            return '模型名称不能为空';
        }
        if (!isset($param['mouldcode']) || !$param['mouldcode']) {
            return '模型编码不能为空';
        }
        if(!preg_match("/^[a-zA-Z]([a-zA-Z0-9_]+)?$/", $param['mouldcode'])) {
            return '模型编码格式不正确';
        }
        $classflag = intval($param['classflag']) == '1' ? '1' : '2';
        $sideflag = intval($param['sideflag']) == '1' ? '1' : '2';
        $tmplflag = intval($param['tmplflag']) == '1' ? '1' : '2';
        $status = intval($param['status']) == '1' ? '1' : '2';
        // 数据修改
        $data['mouldname'] = $param['mouldname'];
        $data['mouldcode'] = $param['mouldcode'];
        $data['viewseq'] = intval($param['viewseq']);
        $data['classflag'] = $classflag;
        $data['sideflag'] = $sideflag;
        $data['tmplflag'] = $tmplflag;
        $data['status'] = $status;
        $data['mouldtype'] = '2';
        $where['id'] = $param['id'];
        $db = $this->conn('mysql');
        $result = $db->updateData('sysmould', $data, $where);
        if (!$result) {
            return '模型配置数据更新失败';
        }

        // 表结构处理
        $tableCode = $db->db_fix.$data['mouldcode'];
        $tableName = $data['mouldname'];
        // 关联多菜单关闭时-删除表
        if($classflag == 2){
            $listRes = $this->delTable($tableCode.'_class');
            if($listRes != 'Y'){return $listRes;}
        }
        // 关联多菜单开启时-创建表
        if($classflag == 1){
            $listRes = $this->createTableClass($tableCode, $tableName);
            if($listRes != 'Y'){return $listRes;}
        }
        // 子集列表关联表-删除表
        if($sideflag == 2){
            $sideRes = $this->delTable($tableCode.'_side');
            if($sideRes != 'Y'){return $sideRes;}
        }
        // 子集列表关联表-创建表
        if($sideflag == 1){
            $sideRes = $this->createTableSide($tableCode, $tableName);
            if($sideRes != 'Y'){return $sideRes;}
        }
        // 自定义详情模版关闭时-删除表
        if($tmplflag == 2){
            $listRes = $this->delTable($tableCode.'_list');
            if($listRes != 'Y'){return $listRes;}
        }
        // 自定义详情模版开启时-创建表
        if($tmplflag == 1){
            $listRes = $this->createTableList($tableCode, $tableName);
            if($listRes != 'Y'){return $listRes;}
        }
        return 'Y';
    }

    /**
     * Notes:创建主表
     * User: ZhuHaili
     */
    private function createTableMain($tableCode, $tableName){
        $table = $tableCode;         // 表名称
        $tableName = $tableName;    // 表注释昵称
        // 创建sql
        $sql = " create table `" . $table . "` (
                      `id` int(10) unsigned not null auto_increment comment 'id',
                      `fid` int(10) unsigned not null default '0' comment '父级id',
                      `menu_id` int(10) unsigned not null default '0' comment '菜单id',
                      `title` varchar(200) character set utf8 collate utf8_general_ci not null comment '标题',
                      `status` char(1) not null default '1' comment '状态（1待审核，2已审核，3未通过）',
                      `viewseq` smallint(5) unsigned not null default 0 comment '展示排序',
                      `createdate` varchar(20) character set utf8 collate utf8_general_ci null comment '创建时间',
                      primary key (`id`) using btree,
                      key `fid` (`fid`) using btree,
                      key `title` (`title`) using btree,
                      key `menu_id` (`menu_id`) using btree,
                      key `status` (`status`) using btree
                    ) engine=innodb default charset=utf8 row_format=dynamic comment='" . $tableName . "';";
        return $this->createTable($table, $sql);
    }

    /**
     * Notes:创建详情表
     * User: ZhuHaili
     */
    private function createTableVice($tableCode, $tableName){
        $table = $tableCode . '_detail';     // 表名称
        $tableName = $tableName.'_详情表';  // 表注释昵称
        // 创建sql
        $sql = " create table `" . $table . "` (
                      `aid` int(10) unsigned not null auto_increment comment 'id',
                      `essay_id` int(10) unsigned not null default '0' comment '文章表id',
                      primary key (`aid`) using btree,
                      KEY `essay_id` (`essay_id`) USING BTREE
                    ) engine=innodb default charset=utf8 row_format=dynamic comment='" . $tableName . "';";
        return $this->createTable($table, $sql);
    }

    /**
     * Notes:创建多菜单关联表
     * User: ZhuHaili
     */
    private function createTableClass($tableCode, $tableName){
        $table = $tableCode . '_class';              // 表名称
        $tableName = $tableName.'_多菜单关联表';     // 表注释昵称
        // 创建sql
        $sql = " create table `" . $table . "` (
                      `cid` int(10) unsigned not null auto_increment comment 'id',
                      `essay_id` int(10) unsigned not null default '0' comment '文章id(外键)',
                      `menu_id` int(10) unsigned not null default '0' comment '菜单id(外键)',
                      primary key (`cid`) using btree,
                      key `essay_id` (`essay_id`) using btree,
                      key `menu_id` (`menu_id`) using btree
                    ) engine=innodb default charset=utf8 row_format=dynamic comment='" . $tableName . "';";
        return $this->createTable($table, $sql);
    }

    /**
     * Notes:创建子集关联表
     * User: ZhuHaili
     */
    private function createTableSide($tableCode, $tableName){
        $table = $tableCode . '_side';               // 表名
        $tableName = $tableName.'_内容子集关联表';   // 表注释昵称
        // 创建sql
        $sql = " create table `" . $table . "` (
                      `id` int(10) unsigned not null auto_increment comment 'id',
                      `fid` int(10) unsigned not null default '0' comment 'fid(外键)',
                      `title` varchar(200) character set utf8 collate utf8_general_ci not null comment '标题',
                      `essay_id` int(10) unsigned not null default '0' comment '文章id(外键)',
                      `menu_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '菜单id',
                      `status` char(1) not null default '1' comment '状态（1待审核，2已审核，3未通过）',
                      `viewseq` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '展示排序',
                      `createdate` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建时间',
                      primary key (`id`) using btree,
                      key `fid` (`fid`) using btree,
                      key `title` (`title`) using btree,
                      key `essay_id` (`essay_id`) using btree,
                      key `menu_id` (`menu_id`) using btree,
                      key `status` (`status`) using btree
                    ) engine=innodb default charset=utf8 row_format=dynamic comment='" . $tableName . "';";
        return $this->createTable($table, $sql);
    }

    /**
     * Notes:创建自定义模版关联表
     * User: ZhuHaili
     */
    private function createTableList($tableCode, $tableName){
        $table = $tableCode . '_list';               // 表名
        $tableName = $tableName.'_自定义模版关联表';   // 表注释昵称
        // 创建sql
        $sql = " create table `" . $table . "` (
                      `lid` int(10) unsigned not null auto_increment comment 'id',
                      `essay_id` int(10) unsigned not null default '0' comment '文章id(外键)',
                      `tpl_id` int(10) unsigned not null default '0' comment '模版id(外键)',
                      `essay_field` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文章字段',
                      `content` text COMMENT '内容',
                      `status` char(1) not null default '1' comment '状态（1待审核，2已审核，3未通过）',
                      `viewseq` smallint(5) UNSIGNED NOT NULL DEFAULT 0 COMMENT '展示排序',
                      `createdate` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建时间',
                      primary key (`lid`) using btree,
                      key `essay_id` (`essay_id`) using btree,
                      key `tpl_id` (`tpl_id`) using btree,
                      key `status` (`status`) using btree
                    ) engine=innodb default charset=utf8 row_format=dynamic comment='" . $tableName . "';";
        return $this->createTable($table, $sql);
    }

    /**
     * Notes:创建表执行
     * User: ZhuHaili
     */
    private function createTable($table, $sql){
        $db = $this->conn('mysql');
        $verifyTable = $this->verifyTable($table);
        if($verifyTable){
            return 'Y'; // 已经存在了无需创建
        }
        $request = $db->query($sql);
        if(!$request){
            return "创建 $table 失败";
        }
        return 'Y';
    }

    /**
     * Notes:删除表执行
     * User: ZhuHaili
     */
    private function delTable($table){
        $verifyTable = $this->verifyTable($table);
        if(!$verifyTable){
            return 'Y'; // 已经不存在了无需删除
        }
        // 表存在时执行删除
        $sql = "drop table $table;";
        $db = $this->conn('mysql');
        $request = $db->query($sql);
        if(!$request){
            return "删除 $table 失败";
        }
        return 'Y';
    }

    /**
     * Notes:验证表是否存在
     * User: ZhuHaili
     */
    public function verifyTable($table){
        $db = $this->conn('mysql');
        $sql = "select count(*) as count from information_schema.tables where table_name='".$table."' and table_schema='".$db->db_name."'";
        $res = $db->query($sql, 1);
        if (isset($res[0]['count']) && $res[0]['count'] > 0) {
            return true; // 表存在
        }
        return false; // 表不存在
    }
}